<template>
  <view class="submit-order">
    <view class="submit-order-student" v-if="goodsInfo && goodsInfo.needCourseFlag === '1'">
      <view class="submit-order-student-add" @click="handleSelectOrderCourse"
        v-if="!orderCourseInfo.studentInfo || !orderCourseInfo.studentInfo.id">
        <uni-icons type="plusempty" size="20" color="#a0a0b3"></uni-icons>
        <view class="submit-order-signup-add-label">人员及课程信息</view>
      </view>
      <view class="submit-order-signup-info" @click="handleSelectOrderCourse" v-if="orderCourseInfo.studentInfo &&
      orderCourseInfo.studentInfo.id &&
      orderCourseInfo.swimPlaceInfo &&
      orderCourseInfo.swimPlaceInfo.id &&
      orderCourseInfo.courseInfo &&
      orderCourseInfo.courseInfo.id
      ">
        <view class="submit-order-signup-item" style="margin-top: 0">
          <view class="submit-order-signup-item-label">游泳馆：</view>{{ orderCourseInfo.swimPlaceInfo.name }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">游泳馆地址:</view>{{ orderCourseInfo.swimPlaceInfo.address }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">游泳课班级:</view>{{ orderCourseInfo.courseInfo.swimPlaceClassName }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">游泳课课程:</view>{{ orderCourseInfo.courseInfo.courseName }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">上课日期:</view>{{ orderCourseInfo.courseInfo.courseStartDate }} ~
          {{ orderCourseInfo.courseInfo.courseEndDate }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">上课时间:</view>{{ orderCourseInfo.courseInfo.courseStartTime }} ~
          {{ orderCourseInfo.courseInfo.courseEndTime }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">上课地址:</view>{{ orderCourseInfo.courseInfo.address }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">学校:</view>{{ orderCourseInfo.studentInfo.schoolName }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">年级:</view>{{ orderCourseInfo.studentInfo.gradeName }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">班级:</view>{{ orderCourseInfo.studentInfo.className }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">学生:</view>{{ orderCourseInfo.studentInfo.studentName }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">家长手机号:</view>{{ orderCourseInfo.studentInfo.parentPhone }}
        </view>
      </view>
    </view>
    <view class="submit-order-student" v-if="goodsInfo && goodsInfo.needCourseFlag === '0'">
      <view class="submit-order-student-add" @click="handleSelectStudent"
        v-if="!orderCourseInfo.studentInfo || !orderCourseInfo.studentInfo.id">
        <uni-icons type="plusempty" size="20" color="#a0a0b3"></uni-icons>
        <view class="submit-order-signup-add-label">学生信息</view>
      </view>
      <view class="submit-order-signup-info" @click="handleSelectStudent"
        v-if="orderCourseInfo.studentInfo && orderCourseInfo.studentInfo.id">
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">学校:</view>{{ orderCourseInfo.studentInfo.schoolName }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">年级:</view>{{ orderCourseInfo.studentInfo.gradeName }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">班级:</view>{{ orderCourseInfo.studentInfo.className }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">学生:</view>{{ orderCourseInfo.studentInfo.studentName }}
        </view>
        <view class="submit-order-signup-item">
          <view class="submit-order-signup-item-label">家长手机号:</view>{{ orderCourseInfo.studentInfo.parentPhone }}
        </view>
      </view>
    </view>
    <view class="submit-order-goods">
      <image class="submit-order-goods-img" mode="aspectFill" :src="goodsInfo.goodsCoverImg" />
      <view class="submit-order-goods-name-intro-price-count">
        <view class="submit-order-goods-name">{{ goodsInfo.goodsName }}</view>
        <view class="submit-order-goods-intro">
          {{ goodsInfo.goodsIntro }}
        </view>
        <view class="submit-order-goods-price-count">
          <view class="submit-order-goods-price">¥{{ goodsInfo.sellingPrice }}</view>
          <uni-number-box :min="1" v-model="goodsInfo.goodsNum" @change="countChange" />
        </view>
      </view>
    </view>
    <view class="submit-order-pay">
      <image src="/static/images/ic_wx_pay.png" class="submit-order-pay-icon" />
      <text class="submit-order-pay-label">微信支付</text>
    </view>
    <view class="submit-order-bottom">
      <view class="submit-order-bottom-sum-count">
        <view class="submit-order-bottom-sum">
          <label class="submit-order-bottom-sum-label">合计：</label>
          <label class="submit-order-bottom-sum-text">¥{{ goodsInfo.totalPrice }}</label>
        </view>
        <view class="submit-order-bottom-count">共{{ goodsInfo.goodsNum }}件</view>
      </view>
      <view class="submit-order-bottom-btn" @click="handleSubmitOrder"> 提交订单 </view>
    </view>
  </view>
</template>

<script setup>
import { showToast, toPage, showLoading, hideLoading } from '@/utils/app.js';

import { WX_LOGIN_INFO } from '@/utils/constants.js';

import { setItem, getItem } from '@/utils/storage.js';

import { onLoad } from '@dcloudio/uni-app';

// import { getGoods } from '@/api/goods.js';

import { createOrder, createPrePayOrder } from '@/api/order.js';

import { getWxCodeInfo } from '@/api/wechat.js';

import { useUserInfoStore } from '@/stores/user';
const userInfoStore = useUserInfoStore();

const goodsInfo = ref({});
onLoad((options) => {
  const params = JSON.parse(decodeURIComponent(options.params));
  goodsInfo.value = params;
});

/**学生信息 */
const orderCourseInfo = ref({});
const bindListener = () => {
  uni.$on('__selectOrderCourse__', function (data) {
    orderCourseInfo.value = data;
  });
  uni.$on('__selectStudent__', function (data) {
    orderCourseInfo.value.studentInfo = data;
  });
};

onMounted(() => {
  bindListener();
});

onUnmounted(() => {
  uni.$off('__selectOrderCourse__');
  uni.$off('__selectStudent__');
});

const handleSelectOrderCourse = () => {
  toPage('/pages/course/SelectOrderCourse');
};

const handleSelectStudent = () => {
  toPage('pages/user/StudentList?source=order');
};

const countChange = (val) => {
  goodsInfo.value.totalPrice = parseFloat(
    (goodsInfo.value.sellingPrice * goodsInfo.value.goodsNum).toFixed(2)
  );
};

const handleSubmitOrder = async () => {
  if (goodsInfo.value.needCourseFlag === '1') {
    if (
      !orderCourseInfo.value.swimPlaceInfo ||
      !orderCourseInfo.value.swimPlaceInfo.id ||
      !orderCourseInfo.value.courseInfo ||
      !orderCourseInfo.value.courseInfo.id ||
      !orderCourseInfo.value.studentInfo ||
      !orderCourseInfo.value.studentInfo.id
    ) {
      return showToast('请添加人员及课程信息');
    }
  } else {
    if (
      !orderCourseInfo.value.studentInfo ||
      !orderCourseInfo.value.studentInfo.id
    ) {
      return showToast('请添加学生信息');
    }
  }

  const params = {
    item: {
      goodsId: goodsInfo.value.id,
      quantity: goodsInfo.value.goodsNum,
      specsId: goodsInfo.value.specsId,
      specsFlag: goodsInfo.value.specsFlag,
    },
    remark: '',
    userId: userInfoStore.userId,
    schoolId: orderCourseInfo.value.studentInfo.schoolId,
    schoolName: orderCourseInfo.value.studentInfo.schoolName,
    gradeId: orderCourseInfo.value.studentInfo.gradeId,
    gradeName: orderCourseInfo.value.studentInfo.gradeName,
    classId: orderCourseInfo.value.studentInfo.classId,
    className: orderCourseInfo.value.studentInfo.className,
    parentName: orderCourseInfo.value.studentInfo.parentName,
    parentPhone: orderCourseInfo.value.studentInfo.parentPhone,
    studentId: orderCourseInfo.value.studentInfo.id,
    studentName: orderCourseInfo.value.studentInfo.studentName,
    payType: 2,
  };

  if (goodsInfo.value.needCourseFlag === '1') {
    params['swimPlaceId'] = orderCourseInfo.value.swimPlaceInfo.id;
    params['courseId'] = orderCourseInfo.value.courseInfo.id;
  }

  const res = await createOrder(params);
  if (res.code === 200) {
    showToast('订单创建成功');
    createPrePayOrderReq(res.data);
  }
};

// 准备支付
const createPrePayOrderReq = (data) => {
  showLoading();
  const orderId = data.id;
  const wxLoginInfo = getItem(WX_LOGIN_INFO);
  if (wxLoginInfo && wxLoginInfo.openid) {
    const openid = wxLoginInfo.openid;
    createPrePayOrder(openid, orderId).then((res) => {
      wxPay(res.data, orderId);
    });
  } else {
    getWxCodeInfoReq(function (openid) {
      createPrePayOrder(openid, orderId).then((res) => {
        wxPay(res.data, orderId);
      });
    });
  }
};

// 获取微信信息
const getWxCodeInfoReq = (callback) => {
  uni.login({
    success: function (res) {
      const code = res.code;
      getWxCodeInfo({ code }).then((res) => {
        setItem(WX_LOGIN_INFO, res.data);
        const openid = res.data.openid;
        callback(openid);
      });
    },
  });
};

const wxPay = (data, orderId) => {
  uni.requestPayment({
    timeStamp: data.timeStamp + '',
    nonceStr: data.nonceStr,
    package: data.prepayId,
    signType: data.signType,
    paySign: data.paySign,
    success: function (res) {
      if (res.errMsg == 'requestPayment:ok') {
        uni.showToast({
          title: '支付成功',
          icon: 'success',
        });
        uni.redirectTo({
          url: '/pages/order/pay-success?payPrice=' + data.payPrice,
        });
      } else {
        uni.showToast({
          title: res.errmsg,
          icon: 'none',
        });
      }
    },
    fail: function (err) {
      console.log('err', err);
      if (err.errMsg == 'requestPayment:fail cancel') {
        uni.showToast({
          title: '支付取消',
          icon: 'none',
        });
      } else {
        uni.showToast({
          title: err.errmsg,
          icon: 'none',
        });
      }
      uni.navigateTo({
        url: '/pages/order/Order-detail?id=' + orderId,
      });
    },
  });
};
</script>

<style scoped lang="scss">
.submit-order {
  display: flex;
  flex-direction: column;
  padding-bottom: 140rpx;

  .submit-order-student {
    display: flex;
    flex-direction: column;

    .submit-order-student-add {
      margin: 24rpx 24rpx 0rpx 24rpx;
      padding: 24rpx;
      border-radius: 16rpx;
      background: #ffffff;
      height: 120rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .submit-order-signup-add-label {
        color: #a0a0b3;
        font-family: PingFang SC;
        font-size: 32rpx;
        margin-left: 4rpx;
      }
    }

    .submit-order-signup-info {
      display: flex;
      flex-direction: column;
      margin: 24rpx 24rpx 0rpx 24rpx;
      padding: 24rpx;
      border-radius: 16rpx;
      background: #ffffff;

      .submit-order-signup-item {
        display: flex;
        color: #202020;
        font-family: PingFang SC;
        font-size: 28rpx;
        margin-top: 16rpx;

        .submit-order-signup-item-label {
          width: 200rpx;
        }
      }
    }
  }

  .submit-order-goods {
    margin: 24rpx 24rpx 0rpx 24rpx;
    padding: 24rpx;
    border-radius: 16rpx;
    background: #ffffff;
    display: flex;

    .submit-order-goods-img {
      width: 170rpx;
      height: 170rpx;
      border-radius: 8rpx;
      background: #eeeeee;
    }

    .submit-order-goods-name-intro-price-count {
      flex: 1;
      margin-left: 16rpx;
      display: flex;
      flex-direction: column;

      .submit-order-goods-name {
        color: #1f242e;
        font-family: PingFang SC;
        font-size: 26rpx;
      }

      .submit-order-goods-intro {
        margin-top: 8rpx;
        color: #828b94;
        font-family: PingFang SC;
        font-size: 24rpx;
      }

      .submit-order-goods-price-count {
        margin-top: 8rpx;
        display: flex;
        align-items: center;

        .submit-order-goods-price {
          color: #c61323;
          font-family: DINPro;
          font-weight: 500;
          font-size: 36rpx;
          flex: 1;
        }
      }
    }
  }

  .submit-order-pay {
    margin: 24rpx 24rpx 0rpx 24rpx;
    padding: 24rpx;
    border-radius: 16rpx;
    background: #ffffff;
    display: flex;
    align-items: center;

    .submit-order-pay-icon {
      width: 40rpx;
      height: 40rpx;
    }

    .submit-order-pay-label {
      margin-left: 16rpx;
      color: #1f242e;
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 28rpx;
    }
  }
}

.submit-order-bottom {
  position: fixed;
  bottom: 0px;
  left: 0px;
  right: 0px;
  padding: 16rpx 32rpx;
  background: #ffffff;
  box-shadow: 0rpx -8rpx 20rpx #949fb340;
  display: flex;
  align-items: center;

  .submit-order-bottom-sum-count {
    display: flex;
    flex-direction: column;
    flex: 1;

    .submit-order-bottom-sum {
      display: flex;
      align-items: center;

      .submit-order-bottom-sum-label {
        color: #1d2129;
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 32rpx;
      }

      .submit-order-bottom-sum-text {
        color: #c61323;
        font-family: DINPro;
        font-weight: 500;
        font-size: 32rpx;
      }
    }

    .submit-order-bottom-count {
      margin-top: 4rpx;
      color: #4e5969;
      font-family: PingFang SC;
      font-size: 24rpx;
      line-height: 34rpx;
    }
  }

  .submit-order-bottom-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16rpx 32rpx;
    border-radius: 24rpx;
    background: linear-gradient(138.98deg, #cb3d3d 0.5%, #a11012 100.24%);
    color: #ffffff;
    font-family: PingFang SC;
    font-weight: 600;
    font-size: 28rpx;
  }
}
</style>
